/**
 * 任务系统错误处理和调试工具
 */

// 错误类型枚举
export const ERROR_TYPES = {
  DATA_MAPPING: 'DATA_MAPPING',
  ROLE_JUDGMENT: 'ROLE_JUDGMENT',
  VALIDATION: 'VALIDATION',
  NETWORK: 'NETWORK',
  UNKNOWN: 'UNKNOWN'
};

// 错误严重程度
export const ERROR_SEVERITY = {
  LOW: 'LOW',
  MEDIUM: 'MEDIUM',
  HIGH: 'HIGH',
  CRITICAL: 'CRITICAL'
};

/**
 * 错误处理器
 */
export class TaskErrorHandler {
  constructor() {
    this.errorLog = [];
    this.maxLogSize = 100;
  }

  /**
   * 记录错误
   * @param {String} type - 错误类型
   * @param {String} message - 错误消息
   * @param {Object} context - 错误上下文
   * @param {String} severity - 错误严重程度
   */
  logError(type, message, context = {}, severity = ERROR_SEVERITY.MEDIUM) {
    const error = {
      id: Date.now() + Math.random(),
      timestamp: new Date().toISOString(),
      type,
      message,
      context,
      severity,
      stack: new Error().stack
    };

    this.errorLog.push(error);
    
    // 保持日志大小限制
    if (this.errorLog.length > this.maxLogSize) {
      this.errorLog.shift();
    }

    // 根据严重程度决定是否显示给用户
    this.handleErrorBySeverity(error);
    
    console.error(`[任务系统错误] ${type}:`, message, context);
  }

  /**
   * 根据严重程度处理错误
   * @param {Object} error - 错误对象
   */
  handleErrorBySeverity(error) {
    switch (error.severity) {
      case ERROR_SEVERITY.CRITICAL:
        uni.showModal({
          title: '系统错误',
          content: '发生严重错误，请重新启动应用',
          showCancel: false
        });
        break;
      case ERROR_SEVERITY.HIGH:
        uni.showToast({
          title: error.message || '操作失败',
          icon: 'none',
          duration: 3000
        });
        break;
      case ERROR_SEVERITY.MEDIUM:
        console.warn('[任务系统]', error.message);
        break;
      case ERROR_SEVERITY.LOW:
        console.log('[任务系统]', error.message);
        break;
    }
  }

  /**
   * 获取错误日志
   * @returns {Array} 错误日志数组
   */
  getErrorLog() {
    return [...this.errorLog];
  }

  /**
   * 清空错误日志
   */
  clearErrorLog() {
    this.errorLog = [];
  }

  /**
   * 获取特定类型的错误
   * @param {String} type - 错误类型
   * @returns {Array} 特定类型的错误数组
   */
  getErrorsByType(type) {
    return this.errorLog.filter(error => error.type === type);
  }
}

// 全局错误处理器实例
export const taskErrorHandler = new TaskErrorHandler();

/**
 * 数据一致性检查器
 */
export class DataConsistencyChecker {
  /**
   * 检查任务数据一致性
   * @param {Object} taskData - 任务数据
   * @returns {Object} 检查结果
   */
  static checkTaskDataConsistency(taskData) {
    const issues = [];
    
    if (!taskData) {
      issues.push({
        type: 'MISSING_DATA',
        message: '任务数据为空',
        severity: ERROR_SEVERITY.HIGH
      });
      return { isValid: false, issues };
    }

    // 检查必需字段
    const requiredFields = ['id', 'title', 'publisherId'];
    requiredFields.forEach(field => {
      if (!taskData[field]) {
        issues.push({
          type: 'MISSING_FIELD',
          message: `缺少必需字段: ${field}`,
          field,
          severity: ERROR_SEVERITY.HIGH
        });
      }
    });

    // 检查角色字段一致性
    if (taskData.publisherId && taskData.acceptorId) {
      if (taskData.publisherId === taskData.acceptorId) {
        issues.push({
          type: 'ROLE_CONFLICT',
          message: '发布者和接收者不能是同一人',
          severity: ERROR_SEVERITY.HIGH
        });
      }
    }

    // 检查时间字段
    if (taskData.expectedDeliveryTime) {
      const time = new Date(taskData.expectedDeliveryTime);
      if (isNaN(time.getTime())) {
        issues.push({
          type: 'INVALID_TIME',
          message: '期望完成时间格式不正确',
          field: 'expectedDeliveryTime',
          severity: ERROR_SEVERITY.MEDIUM
        });
      }
    }

    return {
      isValid: issues.length === 0,
      issues
    };
  }

  /**
   * 检查角色判断一致性
   * @param {Object} taskData - 任务数据
   * @param {String} userId - 用户ID
   * @param {String} expectedRole - 期望角色
   * @returns {Object} 检查结果
   */
  static checkRoleConsistency(taskData, userId, expectedRole) {
    const issues = [];
    
    if (!taskData || !userId) {
      issues.push({
        type: 'MISSING_PARAMS',
        message: '缺少必要参数',
        severity: ERROR_SEVERITY.HIGH
      });
      return { isValid: false, issues };
    }

    const publisherId = taskData.publisherId || taskData.publisher_id;
    const acceptorId = taskData.acceptorId || taskData.acceptor_id;

    // 检查角色判断逻辑
    const actualRole = publisherId === userId ? 'publisher' : 
                      acceptorId === userId ? 'acceptor' : 'none';

    if (expectedRole && expectedRole !== actualRole) {
      issues.push({
        type: 'ROLE_MISMATCH',
        message: `角色不匹配: 期望${expectedRole}, 实际${actualRole}`,
        expectedRole,
        actualRole,
        severity: ERROR_SEVERITY.HIGH
      });
    }

    return {
      isValid: issues.length === 0,
      issues,
      actualRole
    };
  }
}

/**
 * 调试工具
 */
export class TaskDebugger {
  /**
   * 打印任务数据调试信息
   * @param {Object} taskData - 任务数据
   * @param {String} context - 上下文
   */
  static debugTaskData(taskData, context = '') {
    console.group(`[任务调试] ${context}`);
    console.log('任务数据:', taskData);
    
    if (taskData) {
      console.log('基础信息:');
      console.log('  ID:', taskData.id || taskData._id);
      console.log('  标题:', taskData.title);
      console.log('  类型:', taskData.type);
      console.log('  状态:', taskData.status);
      
      console.log('角色信息:');
      console.log('  发布者ID:', taskData.publisherId || taskData.publisher_id);
      console.log('  接收者ID:', taskData.acceptorId || taskData.acceptor_id);
      
      console.log('时间信息:');
      console.log('  期望完成时间:', taskData.expectedDeliveryTime || taskData.expected_delivery_time);
      console.log('  发布时间:', taskData.publishTime || taskData.publish_time);
    }
    
    console.groupEnd();
  }

  /**
   * 打印角色判断调试信息
   * @param {String} userId - 用户ID
   * @param {Object} taskData - 任务数据
   * @param {String} role - 角色
   */
  static debugRoleJudgment(userId, taskData, role) {
    console.group('[角色判断调试]');
    console.log('用户ID:', userId);
    console.log('任务数据:', taskData);
    console.log('判断结果:', role);
    
    if (taskData) {
      const publisherId = taskData.publisherId || taskData.publisher_id;
      const acceptorId = taskData.acceptorId || taskData.acceptor_id;
      
      console.log('字段映射检查:');
      console.log('  publisherId:', publisherId);
      console.log('  acceptorId:', acceptorId);
      console.log('  用户是否为发布者:', publisherId === userId);
      console.log('  用户是否为接收者:', acceptorId === userId);
    }
    
    console.groupEnd();
  }

  /**
   * 性能监控
   * @param {String} operation - 操作名称
   * @param {Function} fn - 执行函数
   * @returns {Promise} 执行结果
   */
  static async monitorPerformance(operation, fn) {
    const startTime = performance.now();
    
    try {
      const result = await fn();
      const endTime = performance.now();
      const duration = endTime - startTime;
      
      console.log(`[性能监控] ${operation} 耗时: ${duration.toFixed(2)}ms`);
      
      if (duration > 1000) {
        taskErrorHandler.logError(
          ERROR_TYPES.UNKNOWN,
          `${operation} 执行时间过长: ${duration.toFixed(2)}ms`,
          { operation, duration },
          ERROR_SEVERITY.LOW
        );
      }
      
      return result;
    } catch (error) {
      const endTime = performance.now();
      const duration = endTime - startTime;
      
      taskErrorHandler.logError(
        ERROR_TYPES.UNKNOWN,
        `${operation} 执行失败: ${error.message}`,
        { operation, duration, error: error.message },
        ERROR_SEVERITY.HIGH
      );
      
      throw error;
    }
  }
}

/**
 * 数据修复工具
 */
export class DataRepairTool {
  /**
   * 修复任务数据
   * @param {Object} taskData - 任务数据
   * @returns {Object} 修复后的数据
   */
  static repairTaskData(taskData) {
    if (!taskData) return null;

    const repaired = { ...taskData };

    // 修复ID字段
    if (!repaired.id && repaired._id) {
      repaired.id = repaired._id;
    }

    // 修复时间字段
    if (repaired.expected_delivery_time && !repaired.expectedDeliveryTime) {
      repaired.expectedDeliveryTime = repaired.expected_delivery_time;
    }

    // 修复角色字段
    if (repaired.publisher_id && !repaired.publisherId) {
      repaired.publisherId = repaired.publisher_id;
    }
    if (repaired.acceptor_id && !repaired.acceptorId) {
      repaired.acceptorId = repaired.acceptor_id;
    }

    // 设置默认值
    repaired.type = repaired.type || 'other';
    repaired.status = repaired.status || 'pending';

    console.log('[数据修复] 修复前:', taskData);
    console.log('[数据修复] 修复后:', repaired);

    return repaired;
  }
}